<template>
  <div style="width: 60%; margin: 10px auto">
    <div style="margin-bottom: 20px">
      <el-select
        v-model="data.typeId"
        placeholder="请选择宠物分类"
        size="large"
        style="width: 200px; margin-right: 10px"
      >
        <el-option
          v-for="item in data.typeList"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        ></el-option>
      </el-select>
      <el-input
        v-model="data.name"
        size="large"
        style="width: 400px; margin-right: 10px"
        placeholder="请输入宠物名称搜索"
      ></el-input>
      <el-button size="large" type="primary" @click="load">搜索</el-button>
      <el-button size="large" @click="reset">重置</el-button>
    </div>

    <div style="margin: 20px 0" v-if="data.total > 0">
      <div class="waterfall-container">
        <div
          class="waterfall-item"
          v-for="item in data.tableData"
          :key="item.id"
        >
          <el-card style="max-width: 100%">
            <template #header>
              <div
                style="font-size: 20px; font-weight: bold; margin-bottom: 10px"
              >
                {{ item.name }}
              </div>
              <el-row>
                <el-col :span="12">宠物类型：{{ item.typeName }}</el-col>
                <el-col :span="12">宠物品种：{{ item.breed }}</el-col>
                <el-col :span="12">宠物性别：{{ item.sex }}</el-col>
                <el-col :span="12">宠物所在地：{{ item.location }}</el-col>
              </el-row>
            </template>

            <img :src="item.photo" style="width: 100%" />
            <template #footer>
              <el-row class="row-bg" justify="end">
                <el-col :span="8">
                  <el-button
                    v-if="!isCanFoster(item.petCloudFosterList)"
                    @click="handleCloudPet(item)"
                    >花费{{ item.amount }}金币云养</el-button
                  >
                  <el-button @click="toDetais(item)" v-else>查看详情</el-button>
                </el-col>
              </el-row>
            </template>
          </el-card>
        </div>
      </div>
    </div>

    <div style="padding: 20px; text-align: center; color: #666" v-else>
      暂无搜索结果...
    </div>

    <div style="margin-top: 20px" v-if="data.total">
      <el-pagination
        @current-change="load"
        layout="total, prev, pager, next"
        :page-size="data.pageSize"
        v-model:current-page="data.pageNum"
        :total="data.total"
      />
    </div>

    <el-dialog v-model="isAddModalShow" title="发布寄养" width="600">
      <el-form ref="addForm" :model="form" :rules="rules">
        <el-form-item label="宠物名称" prop="name" :label-width="120">
          <el-input
            v-model="form.name"
            autocomplete="off"
            placeholder="请输入宠物名称"
          />
        </el-form-item>
        <el-form-item label="宠物类型" prop="typeId" :label-width="120">
          <el-select
            v-model="form.typeId"
            placeholder="请选择宠物分类"
            clearable
          >
            <el-option
              v-for="item in data.typeList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="宠物性别" prop="sex" :label-width="120">
          <el-select v-model="form.sex" placeholder="请选择宠物性别" clearable>
            <el-option label="公" value="公" />
            <el-option label="母" value="母" />
          </el-select>
        </el-form-item>
        <el-form-item label="宠物图片" prop="typeId" :label-width="120">
          <el-upload
            :action="baseUrl + '/files/upload'"
            :headers="{ token: data.user.token }"
            :on-success="handleFileUpload"
            list-type="picture"
          >
            <el-button type="primary">上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item
          label="联系方式类型"
          prop="connectType"
          :label-width="120"
        >
          <el-select
            v-model="form.connectType"
            placeholder="请选择联系方式类型"
            clearable
          >
            <el-option label="手机号" value="手机号" />
            <el-option label="QQ" value="QQ" />
            <el-option label="微信" value="微信" />
            <el-option label="Email" value="Email" />
          </el-select>
        </el-form-item>
        <el-form-item label="联系方式" prop="connect" :label-width="120">
          <el-input
            v-model="form.connect"
            autocomplete="off"
            placeholder="请输入联系方式"
          />
        </el-form-item>

        <el-form-item label="寄养类型" prop="reuse" :label-width="120">
          <el-select
            v-model="form.reuse"
            placeholder="请选择寄养类型"
            clearable
          >
            <el-option label="流浪宠物" value="流浪宠物" />
            <el-option label="宠物转让" value="宠物转让" />
            <el-option label="短期托管" value="短期托管" />
          </el-select>
        </el-form-item>
        <el-form-item label="数量" prop="store" :label-width="120">
          <el-input-number v-model="form.store" autocomplete="off" />
        </el-form-item>
        <el-form-item label="转让方式" prop="transferType" :label-width="120">
          <el-select
            v-model="form.transferType"
            placeholder="请选择转让方式"
            clearable
          >
            <el-option label="快递" value="快递" />
            <el-option label="线下" value="线下" />
          </el-select>
        </el-form-item>
        <el-form-item label="寄养原因" prop="typeId" :label-width="120">
          <el-input
            placeholder="请输入寄养原因"
            type="textarea"
            v-model="form.introduce"
            autocomplete="off"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="isAddModalShow = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确认</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
      title="申请领养"
      v-model="data.formVisibleAudit"
      width="50%"
      destroy-on-close
    >
      <el-form
        ref="formRef"
        :model="data.form"
        :rules="data.rules"
        label-width="150px"
        style="padding: 20px"
      >
        <el-form-item prop="applyName" label="申请人姓名">
          <el-input
            v-model="data.form.applyName"
            placeholder="请输入申请人姓名"
          ></el-input>
        </el-form-item>
        <el-form-item prop="applyPhone" label="申请人电话">
          <el-input
            v-model="data.form.applyPhone"
            placeholder="请输入申请人电话"
          ></el-input>
        </el-form-item>
        <el-form-item prop="applyIdentity" label="申请人身份证号">
          <el-input
            v-model="data.form.applyIdentity"
            placeholder="请输入申请人身份证号"
          ></el-input>
        </el-form-item>
        <el-form-item prop="applyLocation" label="申请人现住地">
          <el-input
            v-model="data.form.applyLocation"
            placeholder="请输入申请人现住地"
          ></el-input>
        </el-form-item>
        <el-form-item prop="isAccessReturnVisit" label="是否接收回访">
          <el-radio-group v-model="data.form.isAccessReturnVisit">
            <el-radio-button label="是" value="是"></el-radio-button>
            <el-radio-button label="否" value="否"></el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="adoptionReasons" label="领养理由">
          <el-input
            :rows="2"
            type="textarea"
            v-model="data.form.adoptionReasons"
            placeholder="请输入领养理由"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="data.formVisibleAudit = false">取 消</el-button>
          <el-button type="primary" @click="apply()">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
    
<script setup>
import { reactive, ref } from "vue";
import request from "@/utils/request.js";
import { ElMessage, ElMessageBox } from "element-plus";
const baseUrl = import.meta.env.VITE_BASE_URL;

const data = reactive({
  user: JSON.parse(localStorage.getItem("xm-user") || "{}"),
  tableData: [],
  pageNum: 1,
  pageSize: 8,
  total: 0,
  name: null,
  img: "",
  typeId: null,
  typeList: [],
  formVisibleAudit: false,
  form: {},
});

window.scrollTo({ top: 0 });

request.get("/petType/selectAll").then((res) => {
  data.typeList = res.data;
});

const load = () => {
  request
    .get("/petFostering/selectPage", {
      params: {
        pageNum: data.pageNum,
        pageSize: data.pageSize,
        name: data.name,
        typeId: data.typeId,
        flag: "1",
      },
    })
    .then((res) => {
      if (res.code === "200") {
        data.tableData = res.data?.list || [];
        data.total = res.data?.total;
      } else {
        ElMessage.error(res.msg);
      }
    });
};
load();
const isCanFoster = async (fosterList) => {
  const res = await request.get("/usernmae");
  const usernmae = res.data;
  for (let i = 0; i < fosterList.length; i++) {
    const element = applyList[i];
    if (element.username == usernmae) {
      return true;
    }
  }
  return false;
};

const handleCloudPet = (data) => {
  ElMessageBox.confirm(
    `是否花费${data.amount}金币云养${data.name}`,
    "云养宠物",
    {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
    }
  ).then(() => {
    request
      .post("/pet/cloud/foster", {
        petId: data.id,
        amount: data.amount,
      })
      .then((res) => {
        if (res.code == 200) {
          ElMessage.success(res.data);
        } else {
          ElMessage.error(res.data);
        }
        load();
      });
  });
  //   data.form.petFosteringId = id;
  //   data.formVisibleAudit = true;
};
import { useRouter } from "vue-router";
const router = useRouter();
const toDetais = (data) => {
    router.push({path: 'PetCloudDetails', query: {id: data.id}})
}
const reset = () => {
  data.name = null;
  data.typeId = null;
  load();
};

const addForm = ref();
const isAddModalShow = ref(false);
const form = reactive({
  name: "",
  typeId: null,
  sex: null,
  connect: "",
  img: "",
  reuse: null,
  connectType: "",
  store: null,
  transferType: null,
  introduce: "",
});
const rules = {
  name: [{ required: true, message: "请输入宠物名称", trigger: "blur" }],
  typeId: [{ required: true, message: "请选择宠物类型", trigger: "blur" }],
  sex: [{ required: true, message: "请选择宠物性别", trigger: "blur" }],
  img: [{ required: true, message: "请选择图片", trigger: "blur" }],
  connect: [{ required: true, message: "请输入联系方式", trigger: "blur" }],
  reuse: [{ required: true, message: "请选择寄养类型", trigger: "blur" }],
  store: [{ required: true, message: "请输入数量", trigger: "blur" }],
  transferType: [
    { required: true, message: "请选择转让方式", trigger: "blur" },
  ],
  introduce: [{ required: true, message: "请输入寄养原因", trigger: "blur" }],
};
const handleAdd = async () => {
  isAddModalShow.value = true;
  await addForm.value.resetFields();
};

const handleFileUpload = (res) => {
  form.img = res.data;
};

const handleSubmit = async () => {
  const valid = await addForm.value.validate();
  if (valid) {
    request.post("/petReuse/add", form).then((res) => {
      if (res.code == 200) {
        ElMessage.success("保存成功");
        isAddModalShow.value = false;
      } else {
        ElMessage.error("操作失败");
      }
    });
  }
};

const apply = () => {
  request.post("/petFostering/apply", data.form).then((res) => {
    if (res.code == 200) {
      data.formVisibleAudit = false;
      load();
      ElMessage.success("操作成功");
    }
  });
};

const isCanApply = (applyList) => {
  for (let i = 0; i < applyList.length; i++) {
    const element = applyList[i];
    if (element.applyUser == "aaa") {
      return true;
    }
  }
  return false;
};
</script>
    
<style  scoped>
.waterfall-container {
  column-count: 2; /* 设置列数 */
  column-gap: 16px; /* 设置列间距 */
}

.waterfall-item {
  break-inside: avoid; /* 防止内容被拆分到多列 */
  margin-bottom: 16px; /* 设置行间距 */
}

@media (max-width: 1200px) {
  .waterfall-container {
    column-count: 2;
  }
}

@media (max-width: 768px) {
  .waterfall-container {
    column-count: 1;
  }
}
</style>